// src/pages/ViewCreatedSurveys.jsx
import React, { useEffect, useState } from 'react';
import {
  Collapse, List, Typography, Spin, message,
  Tag, Button, Space, Input, Switch
} from 'antd';
import { CopyOutlined, SearchOutlined } from '@ant-design/icons';
import { fetchUserSurveys, updateSurveyStatus } from '../services/survey';
import { getEmailFromToken } from '../utils/getemailfromtoken';
import { Pie, Column } from '@ant-design/charts';
import axios from 'axios';
import dayjs from 'dayjs';
import _ from 'lodash';

const { Panel } = Collapse;
const { Text, Link, Paragraph } = Typography;
const { Search } = Input;

const ViewCreatedSurveys = () => {
  const [surveys, setSurveys] = useState([]);
  const [filteredSurveys, setFilteredSurveys] = useState([]);
  const [loading, setLoading] = useState(true);
  const [answersMap, setAnswersMap] = useState({});

  const loadSurveys = async () => {
    const email = getEmailFromToken();
    if (!email) {
      message.error('用户未登录');
      setLoading(false);
      return;
    }

    try {
      const data = await fetchUserSurveys(email);
      setSurveys(data);
      setFilteredSurveys(data);

      // 加载所有问卷的答卷
      for (const survey of data) {
        const res = await axios.get(`/api/surveys/${survey.id}/answers`);
        if (res.data.success) {
          setAnswersMap(prev => ({ ...prev, [survey.id]: res.data.data }));
        }
      }
    } catch (err) {
      message.error('加载问卷失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadSurveys();
  }, []);

  const handleCopy = (url) => {
    navigator.clipboard.writeText(url)
      .then(() => message.success('链接已复制'))
      .catch(() => message.error('复制失败'));
  };

  const handleStatusToggle = async (surveyId, currentStatus) => {
    const targetStatus = currentStatus === 'published' ? 'close' : 'publish';
    try {
      await updateSurveyStatus(surveyId, targetStatus);
      message.success(`状态已切换为 ${targetStatus}`);
      loadSurveys();
    } catch (err) {
      message.error(err.message);
    }
  };

  const filterSurveys = (value) => {
    const filtered = surveys.filter(s => s.title.includes(value));
    setFilteredSurveys(filtered);
  };

  const renderStatistics = (question, qIdx, answers) => {
    const total = answers.length;
    const stats = answers.map(a => a.answers[qIdx]).filter(Boolean);

    if (question.type === 'single') {
      const count = _.countBy(stats);
      const data = Object.keys(count).map(key => {
        const optionIndex = question.options.indexOf(key);
        const optionLabel = optionIndex !== -1 ? String.fromCharCode(65 + optionIndex) : key;
        const percentage = ((count[key] / total) * 100).toFixed(1);
        return { 
          type: `${optionLabel} (${percentage}%)`, 
          value: count[key]
        };
      });
      
      return <Pie data={data} angleField="value" colorField="type" height={300} />;
    }

    if (question.type === 'multiple') {
      // 统计单个选项和组合选项
      const allCombinations = {};
      
      stats.forEach(selectedOptions => {
        // 转换为字母选项
        const optionLetters = selectedOptions.map(option => {
          const optionIndex = question.options.indexOf(option);
          return optionIndex !== -1 ? String.fromCharCode(65 + optionIndex) : option;
        }).sort();
        
        // 统计单个选项
        optionLetters.forEach(letter => {
          allCombinations[letter] = (allCombinations[letter] || 0) + 1;
        });
        
        // 统计组合选项（2个或以上）
        if (optionLetters.length >= 2) {
          const combo = optionLetters.join('');
          allCombinations[combo] = (allCombinations[combo] || 0) + 1;
        }
      });
      
      // 按选项长度排序（单个选项在前，组合选项在后）
      const sortedEntries = Object.entries(allCombinations).sort((a, b) => {
        if (a[0].length !== b[0].length) {
          return a[0].length - b[0].length;
        }
        return a[0].localeCompare(b[0]);
      });
      
      return (
        <List
          size="small"
          dataSource={sortedEntries}
          renderItem={([combo, cnt]) => (
            <List.Item>{combo}: {(cnt / total * 100).toFixed(1)}%</List.Item>
          )}
        />
      );
    }

    if (question.type === 'rating') {
      const count = _.countBy(stats);
      const data = Object.entries(count)
        .map(([score, cnt]) => ({ 
          score: parseInt(score), 
          percent: parseFloat(((cnt / total) * 100).toFixed(1)),
          count: cnt
        }))
        .sort((a, b) => a.score - b.score);
      
      return (
        <div style={{ width: '50vw', height: '400px' }}>
          <Column 
            data={data} 
            xField="score" 
            yField="percent" 
            height={400}
            xAxis={{
              title: {
                text: '分数',
              },
            }}
            yAxis={{
              title: {
                text: '百分比 (%)',
              },
              min: 0,
            }}
            columnStyle={{
              radius: [4, 4, 0, 0],
            }}
            tooltip={{
              title: '评分统计',
              customContent: (title, data) => {
                if (data && data.length > 0) {
                  const item = data[0];
                  return `<div>分数: ${item.data.score}<br/>百分比: ${item.data.percent}%<br/>人数: ${item.data.count}</div>`;
                }
                return '';
              },
            }}
          />
        </div>
      );
    }

    if (question.type === 'text') {
      return (
        <Collapse>
          <Panel header="查看回答" key="1">
            <List 
              size="small" 
              bordered 
              dataSource={stats} 
              renderItem={txt => <List.Item>{txt}</List.Item>} 
            />
          </Panel>
        </Collapse>
      );
    }

    if (question.type === 'location') {
      return (
        <Collapse>
          <Panel header="查看回答" key="1">
            <List 
              size="small" 
              bordered 
              dataSource={stats} 
              renderItem={(location, index) => (
                <List.Item>
                  {index + 1}. {typeof location === 'object' && location.lat && location.lng 
                    ? `经度: ${location.lng}, 纬度: ${location.lat}`
                    : JSON.stringify(location)
                  }
                </List.Item>
              )} 
            />
          </Panel>
        </Collapse>
      );
    }
  };

  const renderQuestions = (questions, answers) => (
    <List
      dataSource={questions}
      renderItem={(q, idx) => (
        <List.Item>
          <div>
            <Text>{idx + 1}. {q.title}</Text>
            {q.options && (
              <div style={{ display: 'flex', gap: 16, marginTop: 8 }}>
                {q.options.map((opt, i) => (
                  <div key={i}>
                    <Text>{String.fromCharCode(65 + i)}. {opt}</Text>
                  </div>
                ))}
              </div>
            )}
            <div style={{ marginTop: 12 }}>{renderStatistics(q, idx, answers)}</div>
          </div>
        </List.Item>
      )}
    />
  );

  return (
    <div>
      <Search
        placeholder="搜索问卷标题"
        prefix={<SearchOutlined />}
        allowClear
        onSearch={filterSurveys}
        style={{ marginBottom: 20, width: 300 }}
      />
      {loading ? <Spin /> : (
        <Collapse accordion expandIconPosition="end">
          {filteredSurveys.map((survey, index) => {
            const link = `https://localhost:5173/surveys/${survey.id}`;
            const formattedTime = dayjs(survey.createdAt).format('YYYY-MM-DD HH:mm');
            const answers = answersMap[survey.id] || [];

            return (
              <Panel
                key={survey.id}
                header={
                 <div style={{ display: 'flex', alignItems: 'center', gap: 40, paddingRight: 16 }}>
  <Text >{index + 1}. {survey.title}</Text>
  <Text type="secondary">{formattedTime}</Text>
  <Text style={{ color: survey.status === 'published' ? 'blue' : 'red' }}>{survey.status}</Text>
  <div style={{ marginLeft: 'auto' }}>
    <Switch
      checked={survey.status === 'published'}
      checkedChildren="发布"
      unCheckedChildren="关闭"
      onClick={() => handleStatusToggle(survey.id, survey.status)}
    />
  </div>
</div>

                }
              >
                <Space direction="vertical" style={{ width: '100%' }}>
                  <div>
                    <Text type="secondary">问卷链接：</Text>
                    <Link href={link} target="_blank">{link}</Link>
                    <Button icon={<CopyOutlined />} size="small" style={{ marginLeft: 8 }} onClick={() => handleCopy(link)}>复制链接</Button>
                  </div>
                  <div>
                    <Text type="secondary">问卷描述：</Text>
                    <Paragraph>{survey.description || '无'}</Paragraph>
                  </div>
                  <div>
                    <Text type="secondary">总填写次数：{answers.length}</Text>
                  </div>
                  <div>
                    <Text strong>问题列表：</Text>
                    {survey.questions && survey.questions.length > 0 ? (
                      renderQuestions(survey.questions, answers)
                    ) : (
                      <Text type="secondary">该问卷暂无题目</Text>
                    )}
                  </div>
                </Space>
              </Panel>
            );
          })}
        </Collapse>
      )}
    </div>
  );
};

export default ViewCreatedSurveys;